依存のインストール
以下の3つをインストールします。
yarn add -D @types/jest jest ts-jest 設定ファイルを作る
以下はsrc/以下のすべての.tsまたは.tsxファイルをテストの対象にするという意味になる設定です。その時の環境に合わせてtestRegexを書き換えることでいろんな環境に合わせれます。
module.exports = {
moduleFileExtensions: ['ts', 'tsx', 'js'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: 'src/.*(/__tests__/.*|.test).tsx?$',
};テストを試す
適当にsrc/index.test.ts辺りでこんなファイルを作ります。
test('test', () => {
expect(1).toBe(1);
});そしてyarn jestでテストが通れば完了です。
tsconfig.json を指定する
global['ts-jest'].tsConfigに使いたいtsconfig.xxx.jsonへのパスを渡すとその設定でテストを実行することができます。
module.exports = {
globals: {
'ts-jest': {
tsConfig: 'tsconfig.test.json',
diagnostics: true,
},
},
};
tsconfig の paths を jest でも効かせる
moduleNameMapperを指定します。
module.exports = {
moduleNameMapper: {
foo: '/src/foo/src/index.ts'
}
};